<template>
  <div class="post-detail-page">
    <el-card shadow="never" v-loading="loading">
      <div v-if="post">
        <div class="post-header">
          <h1 class="post-title">{{ post.title }}</h1>
          <div class="post-actions" v-if="userStore.user">
            <el-button 
              v-if="userStore.user.id === post.userId" 
              type="primary"
              @click="handleEdit"
            >
              编辑
            </el-button>
            <el-button 
              v-if="userStore.user.id === post.userId || isAdmin" 
              type="danger"
              @click="handleDelete"
            >
              删除
            </el-button>
          </div>
        </div>

        <div class="post-meta">
          <el-avatar :src="post.user?.userAvatar" size="small" />
          <span class="username">{{ post.user?.userName || '匿名用户' }}</span>
          <span class="time">{{ formatTime(post.createTime) }}</span>
          <span v-if="post.updateTime" class="time">更新于：{{ formatTime(post.updateTime) }}</span>
        </div>

        <div class="post-tags">
          <el-tag 
            v-for="(tag, i) in post.tagList" 
            :key="i" 
            size="small"
            style="margin-right: 6px"
          >
            {{ tag }}
          </el-tag>
        </div>

        <div class="post-content">
          <MdPreview :model-value="post.content || ''" />
        </div>

        <div class="post-stats">
          <el-button :type="post.hasThumb ? 'primary' : 'default'" @click="handleThumb">
            <el-icon><Star /></el-icon> 点赞 {{ post.thumbNum || 0 }}
          </el-button>
          <el-button :type="post.hasFavour ? 'primary' : 'default'" @click="handleFavour">
            <el-icon><Collection /></el-icon> 收藏 {{ post.favourNum || 0 }}
          </el-button>
        </div>
      </div>
      <div v-else class="empty-state">
        <el-empty description="帖子不存在或已被删除" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Star, Collection } from '@element-plus/icons-vue'
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { PostControllerService } from '../../../generated'
import type { PostVO, DeleteRequest } from '../../../generated'
import { useUserStore } from '../../stores/user.ts'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const isAdmin = computed(() => {
  return userStore.user?.userRole === 'admin'
})

const loading = ref(false)
const post = ref<PostVO | null>(null)
const id = Number(route.params.id)

const fetchPost = async () => {
  loading.value = true
  try {
    const res = await PostControllerService.getPostVoById(id)
    if (res.code === 0 && res.data) {
      post.value = res.data
    } else {
      ElMessage.error(res.message || '获取帖子失败')
    }
  } catch (e) {
    ElMessage.error('网络错误，获取帖子失败')
  } finally {
    loading.value = false
  }
}

const handleEdit = () => {
  router.push({ name: 'Post', query: { edit: id } })
}

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这个帖子吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const request: DeleteRequest = { id }
    const res = await PostControllerService.deletePost(request)
    
    if (res.code === 0) {
      ElMessage.success('删除成功')
      router.push({ name: 'Post' })
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (e: any) {
    if (e !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleThumb = () => {
  ElMessage.info('点赞功能待实现')
}

const handleFavour = () => {
  ElMessage.info('收藏功能待实现')
}

const formatTime = (time?: string) => {
  if (!time) return ''
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

onMounted(fetchPost)
</script>

<style scoped>
.post-detail-page {
  max-width: 1000px;
  margin: 0 auto;
  padding: 16px;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.post-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.post-actions {
  display: flex;
  gap: 8px;
}

.post-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  color: #909399;
  font-size: 14px;
}

.post-tags {
  margin-bottom: 24px;
}

.post-content {
  margin-bottom: 24px;
  min-height: 200px;
}

.post-stats {
  display: flex;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.empty-state {
  padding: 40px;
  text-align: center;
}
</style>